package com.aube.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.view.KeyEvent;

import com.android.volley.cache.ACache;
import com.aube.R;
import com.aube.control.player.AbstractVideoHelper;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.SharedPrefUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UserUtil;

import java.io.File;

/**
 * Created by huyaonan on 16/4/15.
 */
public class ServerSwitchUtil {
    
    private Context mContext;

    private static ServerSwitchUtil mInstance;

    private ServerSwitchUtil(Context context) {
        this.mContext = context;
    }

    public static synchronized ServerSwitchUtil getmInstance(Context context) {
        if(mInstance == null)
            mInstance = new ServerSwitchUtil(context);
        return mInstance;
    }

    public void showSingleBtnDialog(){
        String path = SharedPrefUtil.getInstance(mContext).getString(SharedPrefUtil.API_PATH);
        String[] items = {"线上正式版", "测试服"};
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AlertDialog);
        builder.setTitle("选择服务器");
        builder.setSingleChoiceItems(items, whichServer(path), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                changeServer(which);
                dialog.dismiss();
            }
        });
        builder.setPositiveButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        Dialog dialog = builder.create();
        dialog.show();
    }

    private int whichServer(String path) {
        if(StringUtils.isBlank(path))
            return 0;
        if(OpenApi.ROUTER_ONLINE.equalsIgnoreCase(path))
            return 0;
        else if(OpenApi.ROUTER_TEST.equalsIgnoreCase(path))
            return 1;
        else
            return 0;
    }

    private void changeServer(int index) {
        String msg="";
        String content="";
        String extra = "";
        switch (index) {
            case 1:
                msg = "您选择切换到《测试服》" + extra;
                content = OpenApi.ROUTER_TEST;
                showSelector(msg, content, 1);
                break;
            case 0:
                msg = "您选择切换到《线上正式版》" + extra;
                content = OpenApi.ROUTER_ONLINE;
                showSelector(msg, content, 0);
                break;
        }
    }

    private void showSelector(final String msg, final String content, final int index) {
        showDialog(mContext, "提示", msg, new DialogCallBack() {

            @Override
            public void reDo() {
                clearPluginFiles(mContext);

                SharedPrefUtil.getInstance(mContext).putString(SharedPrefUtil.API_PATH, content);

                OpenApi.setRouter(content);

                ACache.get(mContext).clear();
                UserUtil.logout(mContext);
            }

            @Override
            public void cancelDo() {

            }
        });
    }

    public void showProxyToggle(){
        boolean state = AbstractVideoHelper.ENABLE_SOCKET_PROXY;
        String[] items = {"开", "关"};
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AlertDialog);
        builder.setTitle("负载均衡");
        builder.setSingleChoiceItems(items, whichServer(state), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                changeState(which);
                dialog.dismiss();
            }
        });
        builder.setPositiveButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        Dialog dialog = builder.create();
        dialog.show();
    }

    private int whichServer(boolean path) {
        return path ? 0 : 1;
    }

    private void changeState(int index) {
        String msg="";
        switch (index) {
            case 1:
                msg = "负载均衡:关";
                showSelector(msg, 1);
                break;
            case 0:
                msg = "负载均衡:开";
                showSelector(msg, 0);
                break;
        }
    }

    private void showSelector(final String msg, final int index) {
        showDialog(mContext, "提示", msg, new DialogCallBack() {

            @Override
            public void reDo() {
                AbstractVideoHelper.ENABLE_SOCKET_PROXY = index == 0;
            }

            @Override
            public void cancelDo() {

            }
        });
    }

    public static void clearPluginFiles(Context context) {
        try{
            File file = new File(Environment.getExternalStorageDirectory(), Constant.getPluginDir());
            if(file.exists()) {
                File[] files = file.listFiles();
                if(files != null) {
                    for (int i = 0; i < files.length; i++) {
                        files[i].delete();
                    }
                }
            }

            File filePatch = new File(Environment.getExternalStorageDirectory(), Constant.APATCH_PATH);
            if(filePatch.exists())
                filePatch.delete();

            File fileCache = context.getCacheDir();
            if(fileCache.exists()) {
                File[] files = fileCache.listFiles();
                if(files != null) {
                    for (int i = 0; i < files.length; i++) {
                        files[i].delete();
                    }
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public void showDialog(Context context,String title,String message,final DialogCallBack callBack){
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialog);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (callBack != null) {
                            callBack.reDo();
                        }
                    }
                });
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (callBack != null) {
                            callBack.cancelDo();
                        }
                    }
                });
        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if(keyCode==KeyEvent.KEYCODE_BACK){
                    dialog.dismiss();
                    if(callBack != null){
                        callBack.cancelDo();
                    }
                }
                return false;
            }
        });
        Dialog dialog = builder.create();
        dialog.show();
    }

    public interface DialogCallBack{
        public void reDo();

        public void cancelDo();
    }

}
